package com.chen.ui;

import com.chen.util.AppContext;
import com.chen.util.Constant;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;


public class LoginGUI extends JFrame {
    private JTextField userText;
    private JPasswordField passwordText;
    // 因为需要将管道一层一层往下传，保证一个客户端只有一个管道
    private Socket socket;

    public LoginGUI() {
        super("登录界面");
        initView();
        // 显示窗口
        setVisible(true);
    }

    private void initView() {
        // 创建主窗口
        setSize(300, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 窗口居中显示

        // 设置布局为BorderLayout
        setLayout(new BorderLayout());

        // 用户名标签与输入框
        JPanel userPanel = new JPanel();
        userPanel.setLayout(new FlowLayout());
        JLabel userLabel = new JLabel("用户名:");
        userText = new JTextField(15);
        userPanel.add(userLabel);
        userPanel.add(userText);

        // 密码标签与输入框
        JPanel passwordPanel = new JPanel();
        passwordPanel.setLayout(new FlowLayout());
        JLabel passwordLabel = new JLabel("密    码:");
        passwordText = new JPasswordField(15);
        passwordPanel.add(passwordLabel);
        passwordPanel.add(passwordText);

        // 登录和取消按钮
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        JButton loginButton = new JButton("登录");
        JButton cancelButton = new JButton("取消");

        // 添加按钮到面板
        buttonPanel.add(loginButton);
        buttonPanel.add(cancelButton);

        // 将面板添加到窗口
        add(userPanel, BorderLayout.NORTH);
        add(passwordPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // 登录按钮事件监听器
        loginButton.addActionListener(this::loginButtonActionListener);

        // 取消按钮事件监听器
        cancelButton.addActionListener(this::cancelButtonActionListener);
    }

    // 登录按钮事件监听器
    private void loginButtonActionListener(ActionEvent e) {
        // 获取画面的用户名称
        String username = userText.getText();
        // 将输入框设置空
        userText.setText("");
        String password = new String(passwordText.getPassword());
        passwordText.setText("");
        login(username, password);

        try {
            // 向客户端传入登录信息后，请求服务端的登录返回结果
            DataInputStream in = new DataInputStream(socket.getInputStream());
            boolean isUserNameDuplication = in.readBoolean();
            boolean loginResult = in.readBoolean();

            // 如果用户名称重复
            if (!isUserNameDuplication) {
                if (loginResult) {
                    // 将管道和用户名存入上下文全局类里，
                    // 替代将管道和用户名作为参数传入群聊界面
                    AppContext.getInstance().setUsername(username);
                    new ChatGUI();
                    dispose();
                }
            } else {
                JOptionPane.showMessageDialog(this, "用户名重复，请重新输入！", "警告", JOptionPane.WARNING_MESSAGE);
            }
        } catch (IOException ex) {
            System.out.println("客户端向服务器获取数据失败！");
            ex.printStackTrace();
        }
    }

    // 登录操作，创建通信管道
    private void login(String username, String password) {
        try {
            socket = new Socket(Constant.SERVER_IP, Constant.SERVER_PORT);
            AppContext.getInstance().setClientSocket(socket);
            // 获取管道的输出流
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            // 首先，先发送代表消息类型的数据
            out.writeUTF(Constant.LOGIN_TYPE);
            out.writeUTF(username);
            out.writeUTF(password);
            out.flush();
        } catch (Exception e) {
            System.out.println("在登录时客户端创建通信管道失败，请检查！");
            e.printStackTrace();
        }
    }


    // 取消按钮事件监听器
    private void cancelButtonActionListener(ActionEvent e) {
        System.exit(0);
    }
}